<template>
  <div>
    <div class="permission">
      <el-card>
        <div style="text-align: right">
          <el-button
            type="primary"
            @click="addClick(1, '0')"
          >添加菜单</el-button>
        </div>

        <el-table :data="list" row-key="id">
          <el-table-column label="菜单名称" prop="name" />
          <el-table-column label="权限标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <span v-if="row.type === 1">
                <el-button
                  type="text"
                  @click="addClick(1, row.id)"
                >添加页面</el-button>
                <el-button
                  type="text"
                  @click="addClick(2, row.id)"
                >添加按钮</el-button>
              </span>
              <el-button type="text" @click="edit(row)">编辑权限</el-button>
              <el-button type="text" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 添加的弹框 -->
    <add ref="add" @getData="getData" />
  </div>
</template>

<script>
import { sysPermission, sysPermissionDel } from '@/api/permission'
import add from './components/add.vue'
export default {
  components: { add },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await sysPermission()
      this.list = this.changeData(res.data)
    },
    changeData(arr, str = '0') {
      return arr.filter((item) => {
        if (item.pid === str) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    },
    // 新增按钮
    addClick(type, pid) {
      this.$refs.add.isShow = true
      this.$refs.add.form.type = type
      this.$refs.add.form.pid = pid
      this.$refs.add.mode = 'add'
    },
    // 删除按钮
    del(id) {
      this.$confirm('你确定要删除此下项吗', '提示')
        .then(async() => {
          await sysPermissionDel(id)
          this.$message.success('删除成功')
          this.getData()
        })
        .catch(() => {})
    },
    // 编辑按钮
    edit(row) {
      this.$refs.add.isShow = true
      // 深拷贝数据
      this.$refs.add.form = JSON.parse(JSON.stringify(row))
      // 修改mode 用于区分场景
      this.$refs.add.mode = 'edit'
    }
  }
}
</script>

<style lang="scss" scoped>
.permission {
  padding: 20px;
}
</style>
